import { ref, watch } from 'vue'
import { airspaceListServer } from '@/api'
import _turf from '@/utils/turfUtil'
import { createCircle, calculateCentroid } from '@/utils/common'

export function managementInit() {
  isFly.value = false
  getAirspaceListServer()
  __g.camera.set(537774.029844, 2489244.642656, 6960.361875, -20.365793, -129.461304, 0)
}

// 是否飞行验证
const isFly = ref(false)
export function addBigAndSmallMeisha() {
  isFly.value = true
  getAirspaceListServer() // 只需要大小梅沙
}

const colors = [
  '#00e24f',
  '#00e24f',
  '#00e24f',
  '#00e24f',
  '#00e24f',
  '#00e24f',
  '#00e24f',
  '#00e24f',
  '#00e24f',
  '#00e24f'
]

// 分成两个不同的数组，一个是适飞空域，一个是管制空域，以便第一次添加的时候不闪一下
let guankongArr = []
let shifeiArr = []
let rulerGuankongArr = []
let rulerShifeiArr = []
let markerGuankongArr = []
let markerShifeiArr = []

//添加空域分层
export async function addAirSpace(val) {
  // let { data } = await airspaceListServer()
  // if (isFly.value) data = data.filter((item) => item.id === 51)
  const newdata = markers.value.map((item) => ({
    ...item,
    coordinate: item.pointsGps?.split('_')
  }))

  newdata.push(
    {
      id: 102,
      airspaceName: '盐田区政府',
      airspaceType: '管制空域',
      airspaceArea: 6.5,
      topHeight: '0',
      botHeight: '0',
      geometryType: 2,
      centLng: '',
      centLat: '',
      centRadius: null,
      pointsGps:
        '114.21427477500004,22.554418069000064_114.21999122800003,22.55785501500003_114.21531085700008,22.564570504000073_114.20959424000011,22.561133396000059_114.21427477500004,22.554418069000064',
      coordinate: [
        '114.23192,22.557869,4.352656',
        '114.234251,22.559246,4.223516',
        '114.232468,22.561124,6.487813',
        '114.230711,22.559699,20.193203',
        '114.231686,22.558075,4.255625'
      ]
    },
    {
      id: 103,
      airspaceName: '沙头角口岸',
      airspaceType: '管制空域',
      airspaceArea: 6.5,
      topHeight: '0',
      botHeight: '0',
      geometryType: 2,
      centLng: '',
      centLat: '',
      centRadius: null,
      pointsGps:
        '114.21427477500004,22.554418069000064_114.21999122800003,22.55785501500003_114.21531085700008,22.564570504000073_114.20959424000011,22.561133396000059_114.21427477500004,22.554418069000064',
      coordinate: [
        '114.222277,22.553611,13.318516',
        '114.221474,22.552948,14.272109',
        '114.221501,22.552807,14.024609',
        '114.221667,22.55266,14.290391',
        '114.221222,22.552261,13.86875',
        '114.221234,22.552155,13.378281',
        '114.221202,22.552126,13.489761',
        '114.221423,22.551885,12.838154',
        '114.221597,22.551799,25.076309',
        '114.22223,22.551542,11.187266',
        '114.222681,22.551371,12.189805',
        '114.222974,22.55124,14.084316',
        '114.223234,22.551003,16.344219',
        '114.223935,22.551043,12.014766',
        '114.224277,22.551032,12.300469',
        '114.224374,22.55104,12.025859',
        '114.224519,22.55121,21.355859',
        '114.223248,22.552554,26.182109',
        '114.222388,22.55351,12.920703'
      ]
    },
    {
      id: 104,
      airspaceName: '边防哨所',
      airspaceType: '管制空域',
      airspaceArea: 6.5,
      topHeight: '0',
      botHeight: '0',
      geometryType: 2,
      centLng: '',
      centLat: '',
      centRadius: null,
      pointsGps:
        '114.21427477500004,22.554418069000064_114.21999122800003,22.55785501500003_114.21531085700008,22.564570504000073_114.20959424000011,22.561133396000059_114.21427477500004,22.554418069000064',
      coordinate: [
        '114.313645,22.601641,5.979141',
        '114.31387,22.601933,11.667109',
        '114.314184,22.601879,21.967617',
        '114.314678,22.601558,19.697266',
        '114.315003,22.601076,19.906992',
        '114.31505,22.600715,29.251719',
        '114.315215,22.600215,32.066328',
        '114.315401,22.599843,12.860391',
        '114.314918,22.59946,3.846328',
        '114.314341,22.599294,7.049219',
        '114.314316,22.599302,3',
        '114.314297,22.599399,3',
        '114.314839,22.599515,3',
        '114.31468,22.599691,2.999961',
        '114.314745,22.59976,2.999961',
        '114.314802,22.600157,3.000039',
        '114.313666,22.601558,5.79459'
      ]
    }
  )
  const heights = [
    {
      z: 0,
      h: 120
    },
    {
      z: 125,
      h: 180
    },
    {
      z: 300,
      h: 300
    }
  ]

  const heights01 = [
    {
      z: 600,
      h: 120
    },
    {
      z: 720,
      h: 180
    },
    {
      z: 900,
      h: 300
    }
  ]

  const heights02 = [
    {
      z: 0,
      h: 1000
    },
    {
      z: 1000,
      h: 2000
    },
    {
      z: 2000,
      h: 3000
    }
  ]
  const polygonArr = []
  const customObjectArr = [] // 标尺
  const colorArr = [
    [0, 0.94, 0.476, 0.098],
    [0, 0.55, 0.479, 1],
    [0.55, 0.816, 1, 0.9]
  ]
  const intensityArr = [0.3, 0.8, 0.3]
  newdata.forEach((item, index) => {
    const air =
      item.geometryType === 2
        ? getAir(item)
        : createCircle(
            _turf.transform([Number(item.centLng), Number(item.centLat)]),
            item.centRadius
          )

    if (item.airspaceType === '适飞空域') {
      //试飞区域分三层
      for (let i = 0; i < 3; i++) {
        let newCoordinates = []
        const opolygon = {
          id: 'spaceGrid-' + index + '-' + i, //3DPolygon唯一标识id
          groupId: 'spaceGrid-shifei',
          coordinates: air, //构成3DPolygon的坐标点数组
          height: heights[i].h, //3D多边形的高度
          // intensity: 1, //亮度
          intensity: intensityArr[i], //亮度
          style: 1, //3DPolygon的样式 请参照API开发文档选取枚举
          // style: window.Polygon3DStyle.WideWave, //3DPolygon的样式 请参照API开发文档选取枚举
          generateTop: true, //是否生成顶面
          generateSide: true, //是否生成侧面
          generateBottom: i === 2, //是否生成底面
          color: colorArr[i],
          scalarParameters: [
            {
              name: 'U',
              value: 0
            },
            {
              name: 'V',
              value: 0
            },
            {
              name: '亮度',
              value: intensityArr[i]
            }
            // {
            //   name: '速度',
            //   value: 0
            // }
          ]
        }
        let arr = JSON.parse(JSON.stringify(air))
        arr.forEach((coor) => {
          if (index == 2) {
            newCoordinates.push([coor[0], coor[1], heights01[i].z])
          } else {
            newCoordinates.push([coor[0], coor[1], heights[i].z])
          }
        })
        opolygon.coordinates = newCoordinates
        polygonArr.push(opolygon)
      }
    } else {
      const opolygon = {
        id: 'spaceGrid-' + index, //3DPolygon唯一标识id
        groupId: 'spaceGrid-guankong',
        coordinates: air, //构成3DPolygon的坐标点数组
        color: '#FF4b1e', //3DPolygon颜色
        height: 300, //3D多边形的高度
        intensity: 1.0, //亮度
        style: 1, //3DPolygon的样式 请参照API开发文档选取枚举
        generateTop: true, //是否生成顶面
        generateSide: true, //是否生成侧面
        generateBottom: false //是否生成底面
      }
      polygonArr.push(opolygon)
    }

    if (item.geometryType === 2) {
      // console.log('%c [ item ]-301', 'font-size:13px; background:pink; color:#bf2c9f;', item)
      //矩形空域
      // 添加标尺
      let o1 = {
        id: 'customObject-' + index,
        groupId: item.airspaceType === '适飞空域' ? 'spaceGrid-shifei' : 'spaceGrid-guankong',
        pakFilePath: HostConfig.pakPathQjd, //资源库pak文件路径,推荐使用cloud内置的文件资源管理器加载pak并使用@path方式传入参数
        assetPath: '/JC_CustomAssets/ObjectLibrary/Exhibition/工具/Ruler', //资源目录，自定义对象在pak文件资源包里的相对路径
        // location: [
        //   ..._turf.transform([
        //     Number(item.coordinate[3].split(',')[0]),
        //     Number(item.coordinate[3].split(',')[1])
        //   ]),
        //   index == 2 ? heights01[0].z : 0
        // ], //位置坐标
        location: getZuobiao(item.airspaceName, item, index, heights01),
        rotation: [0, 0, 0], // 世界坐标系旋转
        localRotation: [0, 40, 0], //模型自身旋转
        scale: [1, 1, 1], //模型缩放
        coordinateType: 0,
        smoothMotion: 1, //1: 平滑移动，0: 跳跃移动
        supportAttach: true //不支持贴画贴合
      }
      customObjectArr.push(o1)
    } else {
      //圆形空域
      let o1 = {
        id: 'customObject-' + index,
        groupId: 'spaceGrid-guankong',
        pakFilePath: HostConfig.pakPathQjd, //资源库pak文件路径,推荐使用cloud内置的文件资源管理器加载pak并使用@path方式传入参数
        assetPath: '/JC_CustomAssets/ObjectLibrary/Exhibition/工具/Ruler', //资源目录，自定义对象在pak文件资源包里的相对路径
        location: [..._turf.transform([Number(item.centLng), Number(item.centLat)]), 0], //位置坐标
        rotation: [0, 0, 0], // 世界坐标系旋转
        localRotation: [0, 40, 0], //模型自身旋转
        scale: [1, 1, 1], //模型缩放
        coordinateType: 0,
        smoothMotion: 1, //1: 平滑移动，0: 跳跃移动
        supportAttach: true //不支持贴画贴合
      }
      customObjectArr.push(o1)
    }
  })

  // 每次点击清空一下 防止多点几次卡顿
  guankongArr = []
  shifeiArr = []
  rulerGuankongArr = []
  rulerShifeiArr = []

  polygonArr.forEach((item) => {
    if (item.groupId === 'spaceGrid-guankong') {
      guankongArr.push(item)
    } else {
      shifeiArr.push(item)
    }
  })

  //批量添加3DPolygon
  if (val === 'shifei') {
    await __g.polygon3d.add(shifeiArr)
  } else {
    // markers.value.push(
    //   {
    //     id: 102,
    //     airspaceName: '盐田区政府',
    //     airspaceType: '管制空域',
    //     airspaceArea: 6.5,
    //     topHeight: '0',
    //     botHeight: '0',
    //     geometryType: 2,
    //     centLng: '',
    //     centLat: '',
    //     centRadius: null,
    //     pointsGps:
    //       '114.21427477500004,22.554418069000064_114.21999122800003,22.55785501500003_114.21531085700008,22.564570504000073_114.20959424000011,22.561133396000059_114.21427477500004,22.554418069000064',
    //     coordinate: [
    //       '114.23192,22.557869,4.352656',
    //       '114.234251,22.559246,4.223516',
    //       '114.232468,22.561124,6.487813',
    //       '114.230711,22.559699,20.193203',
    //       '114.231686,22.558075,4.255625'
    //     ]
    //   },
    //   {
    //     id: 103,
    //     airspaceName: '沙头角口岸',
    //     airspaceType: '管制空域',
    //     airspaceArea: 6.5,
    //     topHeight: '0',
    //     botHeight: '0',
    //     geometryType: 2,
    //     centLng: '',
    //     centLat: '',
    //     centRadius: null,
    //     pointsGps:
    //       '114.21427477500004,22.554418069000064_114.21999122800003,22.55785501500003_114.21531085700008,22.564570504000073_114.20959424000011,22.561133396000059_114.21427477500004,22.554418069000064',
    //     coordinate: [
    //       '114.222277,22.553611,13.318516',
    //       '114.221474,22.552948,14.272109',
    //       '114.221501,22.552807,14.024609',
    //       '114.221667,22.55266,14.290391',
    //       '114.221222,22.552261,13.86875',
    //       '114.221234,22.552155,13.378281',
    //       '114.221202,22.552126,13.489761',
    //       '114.221423,22.551885,12.838154',
    //       '114.221597,22.551799,25.076309',
    //       '114.22223,22.551542,11.187266',
    //       '114.222681,22.551371,12.189805',
    //       '114.222974,22.55124,14.084316',
    //       '114.223234,22.551003,16.344219',
    //       '114.223935,22.551043,12.014766',
    //       '114.224277,22.551032,12.300469',
    //       '114.224374,22.55104,12.025859',
    //       '114.224519,22.55121,21.355859',
    //       '114.223248,22.552554,26.182109',
    //       '114.222388,22.55351,12.920703'
    //     ]
    //   },
    //   {
    //     id: 104,
    //     airspaceName: '边防哨所',
    //     airspaceType: '管制空域',
    //     airspaceArea: 6.5,
    //     topHeight: '0',
    //     botHeight: '0',
    //     geometryType: 2,
    //     centLng: '',
    //     centLat: '',
    //     centRadius: null,
    //     pointsGps:
    //       '114.21427477500004,22.554418069000064_114.21999122800003,22.55785501500003_114.21531085700008,22.564570504000073_114.20959424000011,22.561133396000059_114.21427477500004,22.554418069000064',
    //     coordinate: [
    //       '114.313645,22.601641,5.979141',
    //       '114.31387,22.601933,11.667109',
    //       '114.314184,22.601879,21.967617',
    //       '114.314678,22.601558,19.697266',
    //       '114.315003,22.601076,19.906992',
    //       '114.31505,22.600715,29.251719',
    //       '114.315215,22.600215,32.066328',
    //       '114.315401,22.599843,12.860391',
    //       '114.314918,22.59946,3.846328',
    //       '114.314341,22.599294,7.049219',
    //       '114.314316,22.599302,3',
    //       '114.314297,22.599399,3',
    //       '114.314839,22.599515,3',
    //       '114.31468,22.599691,2.999961',
    //       '114.314745,22.59976,2.999961',
    //       '114.314802,22.600157,3.000039',
    //       '114.313666,22.601558,5.79459'
    //     ]
    //   }
    // )
    await __g.polygon3d.add(guankongArr)
    await addmarker3d(markers.value, 'guankong')
  }

  customObjectArr.forEach((item) => {
    if (item.groupId === 'spaceGrid-guankong') {
      rulerGuankongArr.push(item)
    } else {
      rulerShifeiArr.push(item)
    }
  })

  if (val === 'shifei') {
    await __g.customObject.add(rulerShifeiArr)
  }
  //   } else {
  //     await __g.customObject.add(rulerGuankongArr)
  //   }
  //默认隐藏管制空域
  //   await __g.infoTree.hideByGroupId('spaceGrid-guankong')
  // await __g.marker.add(markerArr)
}

export const markers = ref([])

// 获取片区
const getAirspaceListServer = async () => {
  let { data } = await airspaceListServer()
  if (isFly.value) data = data.filter((item) => item.id === 51)
  markers.value = data
    .filter((item) => item.airspaceType === '管制空域' || item.airspaceType === '适飞空域')
    .map((item) => {
      return {
        ...item,
        coordinate: item.pointsGps?.split('_')
      }
    })
}

const getAir = (val) => {
  const newVal = []
  const newcoordinates = []
  val?.coordinate?.forEach((item) => {
    newVal.push(item.split(','))
  })
  newVal.forEach((item) => {
    newcoordinates.push(_turf.transform([Number(item[0]), Number(item[1]), Number(val.topHeight)]))
  })
  return newcoordinates
}

watch(markers, (newVal) => {
  addmarker3d(newVal, 'shifei')
  addAirSpace('shifei')
})

export async function addmarker3d(val, type) {
  // console.log(val)
  if (!val) val = markers.value
  if (isFly.value) return
  const marker3dArr = []
  const BPFunctions = []

  val.forEach((item, index) => {
    const air = getAir(item)
    const coordinate =
      item.geometryType === 2
        ? calculateCentroid(air)
        : _turf.transform([Number(item.centLng), Number(item.centLat)])
    let o = {
      id: 'airspace-' + index,
      groupId: item.airspaceType == '管制空域' ? 'spaceGrid-guankong' : 'spaceGrid-shifei',
      textVisible: false, //3D标注显示文字是否显示文本
      pointName: '3D_UI_B_1', //3D标注展示的特效名称
      pointVisible: true, //3D标注是否显示
      pointScale: index < 2 ? 200 : 150, //3D标注整体缩放比例
      coordinate:
        item.airspaceArea == '管制空域' ? [coordinate[0], coordinate[1], -10] : coordinate, //3D标注的坐标位置 注意：若坐标Z设置高度为0时 autoHeight=true则会显示在物体上方
      coordinateType: 0, //坐标系类型
      range: [1, 100000], //3D标注的可视距离范围：[min,max]，单位：米
      autoHeight: item.airspaceArea == '管制空域' ? false : true, //自动判断下方是否有物体，设置正确高度，默认值：false
      userData: item.airspaceName
    }
    marker3dArr.push(o)

    BPFunctions.push({
      id: 'airspace-' + index,
      functionName: '文字',
      parameters: [
        {
          paramType: 5,
          paramValue: item.airspaceName
        },
        {
          paramType: 2,
          paramValue: 48
        },
        {
          paramType: 6,
          paramValue: [1, 1, 1, 1]
        }
      ]
    })
    if (item.airspaceType == '管制空域') {
      BPFunctions.push(
        {
          id: o.id,
          functionName: '背景',
          parameters: [
            {
              paramType: 3,
              paramValue: 1
            },
            {
              paramType: 3,
              paramValue: 0.5
            },
            {
              paramType: 3,
              paramValue: 10
            },
            {
              paramType: 6,
              paramValue: [1, 0, 0, 1]
            },
            {
              paramType: 6,
              paramValue: [1, 0, 0, 1]
            },
            {
              paramType: 16,
              paramValue: '纵向渐变'
            }
          ]
        },
        {
          id: o.id,
          functionName: '引线',
          parameters: [
            {
              paramType: 3,
              paramValue: 200
            },
            {
              paramType: 16,
              paramValue: '空'
            }
          ]
        }
      )
    }
  })

  markerGuankongArr = []
  markerShifeiArr = []

  marker3dArr.forEach((item) => {
    if (item.groupId === 'spaceGrid-guankong') {
      markerGuankongArr.push(item)
    } else if (item.groupId === 'spaceGrid-shifei') {
      markerShifeiArr.push(item)
    }
  })

  if (type === 'guankong') {
    await __g.marker3d.add(markerGuankongArr)
  } else if (type === 'shifei') {
    await __g.marker3d.add(markerShifeiArr)
  }

  await __g.marker3d.callBPFunction(BPFunctions)
  //默认隐藏管制空域
  //   await __g.infoTree.hideByGroupId('spaceGrid-guankong')
}

export function managementClear() {
  __g.marker3d.clear()
  __g.polygon3d.clear()
  __g.customObject.clear()
}

/**
 * 获取标尺坐标
 */
const getZuobiao = (name, item, index, heights01) => {
  if (name === '大小梅沙片区') {
    return [
      ..._turf.transform([
        Number(item.coordinate[2].split(',')[0]),
        Number(item.coordinate[2].split(',')[1])
      ]),
      0
    ]
  } else if (name === '冷链物流园片区' || name === '正坑水库片区') {
    return [
      ..._turf.transform([
        Number(item.coordinate[1].split(',')[0]),
        Number(item.coordinate[1].split(',')[1])
      ]),
      0
    ]
  } else if (name === '区政府南边中央公园及周边') {
    return [
      ..._turf.transform([
        Number(item.coordinate[4].split(',')[0]),
        Number(item.coordinate[4].split(',')[1])
      ]),
      0
    ]
  } else {
    return [
      ..._turf.transform([
        Number(item.coordinate[3].split(',')[0]),
        Number(item.coordinate[3].split(',')[1])
      ]),
      index == 2 ? heights01[0].z : 0
    ]
  }
}
